<?php
namespace app\api\controller;

/**
 * 微信小程序 - 第三方平台
 * 用于接收授权事件、公众号消息与事件推送
 * @author  YangPan
 * @date    2017-11-22
 */
class Applet extends Base
{
    // 第三方 - 
    protected $vendorEncodingAesKey;
    
    //
    protected $vendorToken;
    
    //
    protected $vendorAppid;
    
    //
    protected $vendorNonce;
    
    /**
     * 定义参数 VENDOR
     */
    public function _initialize()
    {
        parent::_initialize();
    
        $this->vendorAppid = 'wx31c66fb46734f385';
        $this->vendorToken = 'WeiYongApplet';
        $this->vendorEncodingAesKey = '32595572c66b48bebd1a6b48bebd1affec9f1770a72';
        $this->vendorNonce = mt_rand(10000, 99999);
    }
    
    /**
     * 接口首页 - 不能删除
     */
    public function Index ()
    {
        return;
    }
    
    /**
     * 微信小程序 - 授权事件接收处理
     * @return number
     */
    public function accreditNotice ()
    {
        require_once VENDOR_PATH . 'WxDecryptMsg/wxBizMsgCrypt.php';
            
        $encodingAesKey = $this->vendorEncodingAesKey;
        $token = $this->vendorToken;
        $timeStamp = $this->timeStamp;
        $nonce = $this->vendorNonce;
        $appId = $this->vendorAppid;
    
        // XML数据
        if (!empty($GLOBALS['HTTP_RAW_POST_DATA'])) {
            $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
            logWriteInFile('Rqcode', $xml);
        }
        
        // URL带过来的数据
        $post = input('');
        logWriteInFile('Rqcode-request', $post);
                
        $pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
        
        // 解码公众平台推送的消息
        $errCode = $pc->decryptMsg($post['msg_signature'], $post['timestamp'], $post['nonce'], $xml, $msg);
        logWriteInFile('Rqcode-msg', $msg);
        
        // 把解码后的XML转成数组
        $result = json_decode (json_encode (simplexml_load_string ($msg, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        logWriteInFile('Rqcode-array', $result);
        
    }
    
    // 小程序推送消息给第三方 ???
    public function wxToVendor($text)
    {
        
    }
    
    /**
     * 公共上传单张图片接口，图片大小不能超过500KB，上传后图片会被缩略成500*500
     * 
     * @param  string    mstr
     * 
     * @return string
     */
    public function uploadImg()
    {
        $file = new File();
        $res = $file->uploadFile($this->accessData['aid'], 500000, 500, 500);
        
        if (isset($res['err_msg'])) {
            err($res['err_msg']);
        }
        
        suc('success', ['name'=>$res['name']]);
    }
    
}
